package com.zfzs.post.modules.system.rest;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.zfzs.post.ali.AliOssUtils;
import com.zfzs.post.aop.log.Log;
import com.zfzs.post.common.bean.ResponseResult;
import com.zfzs.post.modules.agent.service.dto.AgentDTO;
import com.zfzs.post.service.PictureService;
import com.zfzs.post.utils.SecurityUtils;
import com.zfzs.post.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @description:
 * @author: ck
 * @create: 2019-12-12 10:17
 **/
@RestController
@RequestMapping("upload_img")
public class UploadImgController {

    @Autowired
    private PictureService pictureService;

    /**
     * 上传图片
     *
     * @param file
     * @return
     * @throws Exception
     */
    @Log("上传图片")
    @PostMapping(value = "/set")
    public ResponseResult picture(@RequestParam MultipartFile file, String path) {
        Map<String, Object> map = new HashMap<>();
        String url = "";
        try {
            InputStream input = file.getInputStream();
            String names = file.getOriginalFilename();
            String suffix = names.substring(names.lastIndexOf("."));
            String imgId = StringUtils.getDateString(5);
            url = AliOssUtils.uploadBytes(input, path + "/" + imgId + suffix);
        } catch (IOException e) {
            e.printStackTrace();
        }
        Snowflake snowflake = IdUtil.createSnowflake(1, 1);
        Long id = snowflake.nextId();
        pictureService.save(id, url, String.valueOf(SecurityUtils.getUserId()));
        map.put("imgId", id.toString());
        map.put("url", url);
        return ResponseResult.ok("上传成功", map);
    }

}
